<template>
    <div class="app-container">
      <div class="filter-container">
        <el-select v-model="searchType" placeholder="选择题型" clearable style="width: 200px; margin-right: 10px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="单选题" value="单选题"></el-option>
          <el-option label="多选题" value="多选题"></el-option>
          <el-option label="判断题" value="判断题"></el-option>
          <el-option label="填空题" value="填空题"></el-option>
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索题目内容"
          style="width: 200px; margin-right: 10px;"
          clearable>
        </el-input>
        <el-button class="filter-item" type="primary" @click="handleSearch">搜索</el-button>
        <el-button class="filter-item" type="primary" @click="handleCreate">添加题目</el-button>
      </div>

      <el-table
        :data="pagedQuestionList"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="title"
          label="题目内容"
          width="400">
        </el-table-column>
        <el-table-column
          prop="type"
          label="题型"
          width="100">
        </el-table-column>
        <el-table-column
          prop="score"
          label="分值"
          width="80">
        </el-table-column>
        <el-table-column
          prop="options"
          label="选项"
          width="300">
          <template slot-scope="scope">
            <div v-for="(option, index) in scope.row.options" :key="index">
              {{ option }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="answer"
          label="答案"
          width="100">
        </el-table-column>
        <el-table-column
          label="操作"
          width="150"
          fixed="right"
          align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredQuestionList.length">
        </el-pagination>
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
        <el-form :model="questionForm" ref="questionForm" :rules="rules" label-width="100px">
          <el-form-item label="题目内容" prop="title">
            <el-input type="textarea" v-model="questionForm.title" rows="3"></el-input>
          </el-form-item>
          <el-form-item label="题型" prop="typeId">
            <el-select v-model="questionForm.typeId" placeholder="请选择题型">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分值" prop="score">
            <el-input-number v-model="questionForm.score" :min="1" :max="100"></el-input-number>
          </el-form-item>
          <el-form-item label="选项" prop="options" v-if="questionForm.type !== '填空题'">
            <el-input
              v-for="(option, index) in questionForm.options"
              :key="index"
              v-model="questionForm.options[index]"
              style="margin-bottom: 10px">
              <template slot="prepend">选项 {{ String.fromCharCode(65 + index) }}</template>
            </el-input>
            <el-button type="text" @click="addOption">添加选项</el-button>
          </el-form-item>
          <el-form-item label="答案" prop="answer">
            <el-input v-model="questionForm.answer"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import request from '@/utils/request'
  export default {
    name: 'QuestionBank',
    data() {
      return {
        searchType: '',
        searchKeyword: '',
        currentPage: 1,
        pageSize: 10,
        selectedQuestions: [],
        questionList: [],
        dialogVisible: false,
        dialogTitle: '',
        currentIndex: -1,
        typeList: [],
        questionForm: {
          title: '',
          typeId: '',
          score: 1,
          options: ['', '', '', ''],
          answer: ''
        },
        rules: {
          title: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
          type: [{ required: true, message: '请选择题型', trigger: 'change' }],
          score: [{ required: true, message: '请输入分值', trigger: 'change' }],
          answer: [{ required: true, message: '请输入答案', trigger: 'blur' }]
        }
      }
    },
    computed: {
      filteredQuestionList() {
        return this.questionList.filter(question => {
          const typeMatch = !this.searchType || question.type === this.searchType
          const keywordMatch = !this.searchKeyword || 
            question.title.toLowerCase().includes(this.searchKeyword.toLowerCase())
          return typeMatch && keywordMatch
        })
      },
      pagedQuestionList() {
        const start = (this.currentPage - 1) * this.pageSize
        const end = start + this.pageSize
        return this.filteredQuestionList.slice(start, end)
      }
    },
    created() {
      this.fetchTypeList()
      this.fetchQuestionList()
    },
    methods: {
      async fetchTypeList() {
        const res = await request.get('/api/questionType/list')
        if (res.code === '200') {
          this.typeList = res.data
        }
      },
      async fetchQuestionList() {
        try {
          const res = await request({
            url: '/api/questionBank/list',
            method: 'get'
          })
          if (res.code === '200') {
            // options 字段为 JSON 字符串，需转为数组
            this.questionList = res.data.map(q => ({
              ...q,
              options: q.options ? JSON.parse(q.options) : []
            }))
          }
        } catch (error) {
          this.$message.error('获取题库失败')
        }
      },
      handleSearch() {
        this.currentPage = 1
      },
      handleSelectionChange(val) {
        this.selectedQuestions = val
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
      },
      handleCurrentChange(val) {
        this.currentPage = val
      },
      handleCreate() {
        this.dialogTitle = '添加题目'
        this.questionForm = {
          title: '',
          type: '',
          score: 1,
          options: ['', '', '', ''],
          answer: ''
        }
        this.currentIndex = -1
        this.dialogVisible = true
      },
      handleEdit(index, row) {
        this.dialogTitle = '编辑题目'
        this.currentIndex = index
        // 深拷贝，防止直接修改表格数据
        this.questionForm = {
          ...row,
          options: Array.isArray(row.options) ? [...row.options] : []
        }
        this.dialogVisible = true
      },
      async handleDelete(index, row) {
        this.$confirm('确认删除该题目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await request({
            url: '/api/questionBank/delete',
            method: 'post',
            params: { id: row.id }
          })
          this.questionList.splice(index, 1)
          this.$message.success('删除成功!')
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      addOption() {
        this.questionForm.options.push('')
      },
      submitForm() {
        this.$refs.questionForm.validate(async (valid) => {
          if (valid) {
            const formData = {
              ...this.questionForm,
              options: JSON.stringify(this.questionForm.options)
            }
            if (this.currentIndex === -1) {
              // 新增
              await request({
                url: '/api/questionBank/create',
                method: 'post',
                data: formData
              })
              this.fetchQuestionList()
            } else {
              // 编辑
              await request({
                url: '/api/questionBank/update',
                method: 'post',
                data: { ...formData, id: this.questionForm.id }
              })
              this.fetchQuestionList()
            }
            this.dialogVisible = false
            this.$message.success(this.dialogTitle === '添加题目' ? '添加成功!' : '修改成功!')
          }
        })
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    padding: 20px;
  }
  
  .filter-container {
    padding-bottom: 20px;
  }
  
  .el-dialog {
    .el-select {
      width: 100%;
    }
  }
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 20px;  /* 添加内边距 */
  background-color: #fff;  /* 添加背景色 */
}
  </style>